package com.smile.job.aspect;

import com.xxl.job.core.context.XxlJobHelper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
public class XxlJobMonitorAspect {
    @Before("@annotation(com.xxl.job.core.handler.annotation.XxlJob)")
    public void doBefore(JoinPoint joinPoint) {
        log.info("======start doBefore========");
        log.info("执行调度的类名为:{}", joinPoint.getSignature().getDeclaringType().getName());
        log.info("执行调度的方法为:{}", joinPoint.getSignature().getName());
        log.info("执行任务的参数为:{}", XxlJobHelper.getJobParam());
        log.info("jobId:{}", XxlJobHelper.getJobId());

        RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(new MockHttpServletRequest()));
        log.info("======end doBefore========");
    }

    @After("@annotation(com.xxl.job.core.handler.annotation.XxlJob)")
    public void doAfter(JoinPoint joinPoint) {
        log.info("======start After========");
        log.info("执行调度的类名为:{}", joinPoint.getSignature().getDeclaringType().getName());
        log.info("执行调度的方法为:{}", joinPoint.getSignature().getName());
        log.info("jobId:{}", XxlJobHelper.getJobId());
        log.info("执行任务的参数为:{}", XxlJobHelper.getJobParam());
        if (XxlJobHelper.handleSuccess()) {
            log.info("======任务执行成功========");
        } else {
            log.info("======任务执行失败========");
        }
        log.info("======end After========");
    }
}
